const query = require('../db/mysql')
const { SuccessModel, ErrorModel } = require('../model')
class BlogController {
    async getBlog(ctx) {
        // 获取列表  分页 模糊查询  排序  条件查询
        // where 模糊查询 条件查询
        const { pageIndex, pageSize, keyword, sortBy, sortType, id } = ctx.query;
        let sql = `select * from blogs where 1=1 ` // 1=1 方便拼接 没别的意思
        let sqlCount = `select count(id) as total from blogs where 1=1 ` // 获取所有带id数据的条数
        // where order limit
        if (keyword) {  // 模糊查询
            sql += `and title like "%${keyword}%" ` // includes
            sqlCount += `and title like "%${keyword}%" `
        }
        if (id) { // 条件查询
            sql += `and id=${id} ` // ==
            sqlCount += `and id=${id} `
        }
        if (sortBy && sortType) { // 排序
            sql += `order by ${sortBy} ${sortType} `
        }
        if (pageIndex && pageSize) { // 分页
            sql += `limit ${(pageIndex - 1) * pageSize},${pageSize}`
        }
        // select * from blogs where 1=1  and title like "%xxx%"  and id=1 order by id desc limit 0,10
        // 调用sql语句
        const res = await query(sql)
        const [{ total }] = await query(sqlCount)
        ctx.body = new SuccessModel({ data: res, total }, '请求成功')
    }
    async delBlog(ctx) {
        // 根据id删除
        // query params body
        const { id } = ctx.params;
        const sql = `delete from blogs where id=${id}`
        const res = await query(sql)
        if (res.affectedRows === 1) {
            ctx.body = new SuccessModel("删除成功");
        } else {
            ctx.body = new ErrorModel("删除失败");
        }

    }
    async editBlog(ctx) {
        // 标题 内容
        const { title, content, id } = ctx.request.body;
        const sql = `update blogs set title="${title}",content="${content}" where id="${id}"`
        const res = await query(sql)
        if (res.affectedRows === 1) {
            ctx.body = new SuccessModel("更新成功");
        } else {
            ctx.body = new ErrorModel("更新失败");
        }
    }
    async addBlog(ctx) {
        // 标题 内容
        const { title, content, author } = ctx.request.body;
        const sql = `insert into blogs(title,content,author,create_time) values("${title}","${content}","${author}","${Date.now()}")`
        const res = await query(sql)
        if (res.affectedRows === 1) {
            ctx.body = new SuccessModel("添加成功");
        } else {
            ctx.body = new ErrorModel("添加失败");
        }
    }
}
module.exports = new BlogController()